import React, { useEffect, useState, useCallback, Fragment } from 'react';
import { connect } from 'umi';
import { Form, Table, Card, Button } from 'antd';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { history } from 'umi';
import LinkTo from '@/components/LinkTo';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import Pagination from '@/components/Pagination';
import { getTempDetail } from '@/services/myRecruit/talentPool';
import SendMail from './Components/SendMail';
import CancelInterview from './Components/CancelInterview';
import SearchForm from './Components/SearchForm';
import styles from './TerviewList.less';

const AdminInterview = ({ dispatch, form, interview, user, loading, location }) => {
    const {
        adminpagination,
        orderBy,
        queryallinterviewsList,
        interviewTypeList,
        interviewConclusionTypeList
    } = interview;
    const { query } = location;
    const [interviewTypeValue, setinterviewTypeValue] = useState([]);
    const [interviewConclusionValue, setinterviewConclusionValue] = useState([]);
    const [tempInfo, setTempInfo] = React.useState({}); // 控制邮件模板类型
    const [candidateCode, setCandidateCode] = React.useState('');
    const [mailModle, setMailModle] = React.useState(); // 控制发送候选人邮件模态框
    const [cancelInfo, setCancelInfo] = React.useState();
    const [cancelInterview, setCancelInterview] = React.useState(false);
    const [sorterInfo, setSorterInfo] = useState();
    const [filtersInfo, setFiltersInfo] = useState();
    const User = user.currentUser; // 登陆人信息
    const handleOpenMile = useCallback(async record => {
        const res = await getTempDetail({
            interviewArrangeCode: record.interviewArrangeCode,
            talentCode: record.talentCode
        });
        if (res && res.code === 10000) {
            setTempInfo({
                ...res.data,
                talentCode: record.talentCode,
                talentEmail: record.talentEmail,
                key: res.data.key
            });
            setMailModle(true);
        }
        setCandidateCode(record.candidateCode);
    }, []);
    // 表格操作返回项
    const actionReturn = record => {
        if (record.isEditArrange) {
            return (
                <Fragment>
                    <LinkTo
                        onClick={async (e, url) => {
                            await eventTrack({
                                eventName: 'personnel_management_recruit_interview_operator_click',
                                eventProps: {
                                    label: '面试管理-操作-修改面试'
                                }
                            });
                            history.push(url);
                        }}
                        to="/office/personnelManagement/recruit/interview/edit"
                        query={{
                            arrangeCode: record.interviewArrangeCode,
                            code: record.candidateCode,
                            type: 'type1'
                        }}
                    >
                        修改面试
                    </LinkTo>
                    <a
                        style={{ display: ' block' }}
                        onClick={e => {
                            eventTrack({
                                eventName: 'personnel_management_recruit_interview_operator_click',
                                eventProps: {
                                    label: '面试管理-操作-取消面试'
                                }
                            });
                            e.preventDefault();
                            setCancelInfo({
                                candidateCode: record.candidateCode,
                                interviewArrangeCode: record.interviewArrangeCode,
                                interviewEmployeeCode: record.interviewEmployeeCode,
                                interviewEmployeeName: record.interviewEmployeeName,
                                interviewRecordCode: record.interviewRecordCode,
                                interviewTime: record.interviewTime,
                                interviewTypeValue: record.interviewTypeValue,
                                talentName: record.talentName
                            });
                            setCancelInterview(true);
                            // handleOpenMile(record);
                        }}
                    >
                        取消面试
                    </a>
                    <a
                        onClick={e => {
                            eventTrack({
                                eventName: 'personnel_management_recruit_interview_operator_click',
                                eventProps: {
                                    label: '面试管理-操作-通知候选人'
                                }
                            });
                            e.preventDefault();
                            handleOpenMile(record);
                        }}
                    >
                        通知候选人
                    </a>
                </Fragment>
            );
        }

        return (
            <LinkTo
                onClick={async (e, url) => {
                    await eventTrack({
                        eventName: 'personnel_management_recruit_interview_operator_click',
                        eventProps: {
                            label: '面试管理-操作-面试详情'
                        }
                    });
                    history.push(url);
                }}
                to="/office/personnelManagement/recruit/interview/edit"
                query={{
                    arrangeCode: record.interviewArrangeCode,
                    code: record.candidateCode,
                    type: 'type3'
                }}
            >
                面试详情
            </LinkTo>
        );
    };
    const getSexName = key => {
        if (key === '1') {
            return (
                <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />
            );
        }
        if (key === '2') {
            return (
                <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />
            );
        }
        return '';
    };
    const getName = list => (
        <Fragment>
            <div className={styles.colum_info_1}>
                <div
                    title={list.talentName}
                    style={{
                        display: 'inline-block',
                        maxWidth: '200px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        verticalAlign: ' text-bottom'
                    }}
                >
                    {list.isEditArrange ? (
                        <LinkTo
                            className={styles.LinkTo}
                            to="/office/personnelManagement/recruit/interview/edit"
                            query={{
                                arrangeCode: list.interviewArrangeCode,
                                code: list.candidateCode,
                                type: 'type1'
                            }}
                        >
                            {list.talentName}
                        </LinkTo>
                    ) : (
                        <LinkTo
                            onClick={async (e, url) => {
                                // 埋点
                                await eventTrack({
                                    eventName: 'personnel_management_recruit_interview_detail_click',
                                    eventProps: {
                                        label: '面试管理-面试详情'
                                    }
                                });
                                history.push(url);
                            }}
                            className={styles.LinkTo}
                            to="/office/personnelManagement/recruit/interview/edit"
                            query={{
                                arrangeCode: list.interviewArrangeCode,
                                code: list.candidateCode,
                                type: 'type3'
                            }}
                        >
                            {list.talentName}
                        </LinkTo>
                    )}
                </div>
                {getSexName(list.talentSex)}
            </div>
        </Fragment>
    );
    const columns = [
        {
            title: '姓名',
            dataIndex: 'talentName',
            key: 'talentName',
            fixed: 'left',
            width: 160,
            render: (text, record) => getName(record)
        },
        {
            title: '应聘职位',
            dataIndex: 'recruitPost',
            key: 'recruitPost',
            fixed: 'left',
            width: 160
        },
        {
            title: '公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200
        },
        {
            title: '面试时间',
            dataIndex: 'interviewTime',
            key: 'interviewTime',
            sorter: () => {},
            width: 200
        },
        {
            title: '面试类型',
            dataIndex: 'interviewTypeValue',
            key: 'interviewTypeValue',
            filters: interviewTypeList,
            width: 180
        },
        {
            title: '面试结果',
            dataIndex: 'interviewConclusionValue',
            key: 'interviewConclusionValue',
            filters: interviewConclusionTypeList,
            width: 180
        },
        {
            title: '评分',
            dataIndex: 'interviewScore',
            key: 'interviewScore',
            sorter: () => {},
            width: 120,
            render: text => {
                if (text || text === 0) {
                    return `${text} 分`;
                }
                return '--';
            }
        },
        {
            title: '面试官',
            dataIndex: 'interviewEmployeeName',
            key: 'interviewEmployeeName',
            width: 140
        },
        {
            title: '招聘负责人',
            dataIndex: 'interviewLeaderName',
            key: 'interviewLeaderName'
            // width: 140
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => actionReturn(record),
            width: 120,
            fixed: 'right'
        }
    ];

    const getListDict = () => {
        dispatch({
            type: 'interview/getListDict'
        });
    };
    const changeTable = (pagination, filters, sorter) => {
        const extra = {};
        if (filtersInfo !== filters) {
            extra.current = 1;
            setFiltersInfo(filters);
        }
        if (sorterInfo !== sorter) {
            extra.current = 1;
            setSorterInfo(sorter);
        }
        let orderBys;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'interviewTime') {
                sorterField = 'interview_time';
            }
            if (sorter.field === 'interviewScore') {
                sorterField = 'interview_score';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBys = `${sorterField} ${order}`;
        }

        if (filters && filters.interviewTypeValue) {
            setinterviewTypeValue(filters.interviewTypeValue);
        }
        if (filters && filters.interviewConclusionValue) {
            setinterviewConclusionValue(filters.interviewConclusionValue);
        }
        dispatch({
            type: 'interview/save',
            payload: {
                orderBy: orderBys || '',
                adminpagination: {
                    ...interview.adminpagination,
                    ...pagination,
                    ...extra
                }
            }
        });
    };
    const getPayload = type => {
        const {
            candidateName,
            insertDate,
            companyId,
            interviewEmployeeId,
            interviewLeaderId,
            recruitCode
        } = form.getFieldsValue();
        const payload = {
            candidateName: candidateName || '',
            companyId: companyId || user.currentUser.companyId,
            beginTime: insertDate && insertDate.length > 0 ? moment(insertDate[0]).format('YYYY-MM-DD 00:00:00') : '',
            endTime: insertDate && insertDate.length > 0 ? moment(insertDate[1]).format('YYYY-MM-DD 23:59:59') : '',
            interviewEmployeeCodes: interviewEmployeeId || [],
            interviewLeaderIds: interviewLeaderId || [],
            recruitCode: recruitCode || '',
            interviewType: interviewTypeValue,
            interviewConclusion: interviewConclusionValue,

            orderByField: orderBy,
            pageNo: type ? 1 : adminpagination.current,
            pageSize: type ? 10 : adminpagination.pageSize
        };
        return payload;
    };
    // 高级搜索
    const handleSearch = type => {
        dispatch({
            type: 'interview/queryallinterviews',
            payload: getPayload(type)
        });
    };

    useEffect(
        () => () => {
            dispatch({
                type: 'interview/save',
                payload: {
                    orderBy: '',
                    adminpagination: {
                        ...adminpagination,
                        pageSize: 10,
                        current: 1
                    }
                }
            });
        },
        []
    );

    // 初始化查询参数，用于 URL 参数化
    const initFields = React.useCallback(() => {
        const { beginTime, endTime, companyId } = query;
        form.setFieldsValue({
            companyId,
            insertDate: beginTime ? [moment(beginTime), moment(endTime)] : [],
            candidateName: query.candidateName || '',
            interviewEmployeeCode: query.interviewEmployeeIds ? query.interviewEmployeeIds.split('-').map(Number) : [],
            interviewLeaderId: query.interviewLeaderIds ? query.interviewLeaderIds.split('-').map(Number) : [],
            recruitCode: query.recruitCode || '',
            interviewType: query.interviewTypeValue,
            interviewConclusion: query.interviewConclusion
        });
    }, [form]);

    useEffect(() => {
        initFields();
        getListDict();
    }, []);

    useEffect(() => {
        const {
            query: { name }
        } = location;
        if (name) {
            form.setFieldsValue(
                {
                    candidateName: name
                },
                () => {
                    handleSearch();
                }
            );
        } else {
            handleSearch();
        }
    }, [adminpagination.pageSize, adminpagination.current, orderBy, interviewConclusionValue, interviewTypeValue]);

    return (
        <PageHeaderWrapper>
            <Card
                bordered={false}
                title="面试管理"
                extra={
                    <Button
                        type="primary"
                        style={{ marginLeft: 16 }}
                        onClick={async () => {
                            await eventTrack({
                                eventName: 'personnel_management_recruit_interview_add_click',
                                eventProps: {
                                    label: '面试管理-发起面试'
                                }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/recruit/interview/add',
                                query: {
                                    type: 'type0'
                                }
                            });
                        }}
                    >
                        发起面试
                    </Button>
                }
            >
                <SearchForm
                    form={form}
                    user={User}
                    onSearch={e => {
                        const { eType } = e;
                        const { interviewEmployeeId, interviewLeaderId } = form.getFieldsValue();
                        history.push({
                            query: {
                                ...query,
                                ...getPayload(1),
                                interviewLeaderIds: interviewLeaderId ? interviewLeaderId.join('-') : '',
                                interviewEmployeeIds: interviewEmployeeId ? interviewEmployeeId.join('-') : ''
                            }
                        });
                        handleSearch(1);
                        // 埋点
                        eventTrack({
                            eventName:
                                eType === 'submit'
                                    ? 'personnel_management_recruit_interview_search_click'
                                    : 'personnel_management_recruit_interview_reset_click',
                            eventProps: {
                                label: eType === 'submit' ? '面试管理-搜索' : '面试管理-清空',
                                key_word: eType === 'submit' ? JSON.stringify(form.getFieldsValue()) : null
                            }
                        });
                    }}
                    identity="admin"
                />
                <Table
                    loading={loading.effects['interview/queryallinterviews']}
                    dataSource={queryallinterviewsList}
                    columns={columns}
                    scroll={{ x: 'max-content' }}
                    onChange={changeTable}
                    rowKey="id"
                    pagination={false}
                />
                <Pagination
                    {...adminpagination}
                    onChange={changeTable}
                    filters={filtersInfo}
                    sorter={sorterInfo}
                    loading={loading.effects['interview/queryallinterviews']}
                />
            </Card>
            <CancelInterview
                visible={cancelInterview}
                setVisible={setCancelInterview}
                data={{ cancelInfo, handleSearch }}
                onCancel={() => {
                    setCancelInterview(false);
                }}
            />
            <SendMail
                form={form}
                visible={mailModle}
                setMailModle={setMailModle}
                data={{ tempInfo, candidateCode }}
                onCancel={() => {
                    setMailModle(false);
                }}
            />
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ loading, interview, user }) => ({
        user,
        interview,
        loading
    }))(Form.create()(AdminInterview))
);
